import {
    getBusinessInfo, 
    toast
} from 'nc-lightapp-front';

let businessInfo = getBusinessInfo() || {};

import CommonAction from '../../../public/actions/employing/common';
import instance from '../main/instance';

export default class FormAction extends CommonAction {
    constructor(comp, context) {
        super();
        this.comp = context || comp;
    }

    // 表单进入编辑态
    toEditStatus = async (formValue, disabled = {}) => {
        const {props} = this.comp;
        const {form, dispatch, button, emp, meta} = props;
        const template = meta.getMeta();

        // 表单进入编辑
        form.setFormStatus('card', 'edit');
        // 按钮进入编辑的按钮
        await this.update({
            addPageStatus: 'edit'
        });

        if(formValue) {
            form.setAllFormValue({
                card: formValue
            });
        }

        // 展开子表
        template['formrelation']['card'].map((item) => {
            form.openArea(item);
        });

        setTimeout(() => {
            form.setFormItemsDisabled('card', {
                ...disabled,
                newpk_org: false,
                newpk_psncl: false,
                newpk_dept: false
            });
        }, 1);

        // instance.pageIns.myForm.card.state.disabled = {};
        
        this.comp.setState({});
    }

    // 表单进入浏览态
    toBrowseStatus = (formValue, isApprove) => {
        const {props} = this.comp;
        const {form, dispatch, button, emp, meta, cardPagination} = props;
        const template = meta.getMeta();

        let showBtn = !emp.fromApprove;
        let billState = '';
        let billId = '';
        // 表单进入编辑
        form.setFormStatus('card', 'browse');
        // 填充表单的值
        if(formValue) {
            form.setAllFormValue({
                card: formValue
            });

            billState = formValue.rows[0].values['workflow_state'].value;
            billId = formValue.rows[0].values['pk_hi_stapply'].value;
        }
        else {
            let allValues = form.getAllFormValue('card').rows[0].values;
            billState = allValues['workflow_state'].value;
            billId = allValues['pk_hi_stapply'].value;
        }
        if(!isApprove) {
            isApprove = emp.isApprove && emp.isApprove[billId];
        }
        console.log(formValue)
        // 按钮进入编辑的按钮
        this.update({
            addPageStatus: 'browse'
        });
        // 隐藏掉一些按钮
            button.setButtonVisible({
                add: showBtn,
                query: false,
                assfunc: true,
                print: true,
                batchadd: false,
                refresh: showBtn,
                callback: showBtn && ['3'].includes(billState),
                edit: (!showBtn && ['3', '2'].includes(billState)) || ['-1'].includes(billState),
                delete: showBtn && ['-1'].includes(billState),
                copy: showBtn && ['0'].includes(billState),
                submit: showBtn && ['-1', '3'].includes(billState),
                excute: !!(isApprove && billState === '1'), // 1 审批通过  // 必须是审批流 和审批通过 1   工作流不能执行
                cardrpt: true,
                file: true
            });
        button.setButtonDisabled({
            edit: false,
            delete: false,
            copy: false,
            submit: emp.fromApprove,
            callback: emp.fromApprove,
            assfunc: false,
            print: false,
            output: false,
            excute: !(isApprove && billState === '1')
        });
        // 展开子表
        template['formrelation']['card'].map((item) => {
            form.openArea(item);
        });

        // 设置当前卡片id给卡片页的翻页使用
        setTimeout(() => {
            cardPagination.setCardPaginationId({
                id: billId,
                status: 1
            });
         },1);
    }

    // 进入到新增页面
    toAddPage = async () => {
        const {props} = this.comp;
        const {form, dispatch, emp, meta} = props;

        this.clearFormValue();
        if(!emp.leaveType) {
            toast({
                color: 'danger',
                content: emp.language['gx6008-000081'] // 当前选择的离职业务类型为空，不能进行后续操作
            });
            return;
        }

        form.EmptyAllFormValue('card');
       
        try {
            let res = await dispatch({
                type: 'emp/checkToAddPage',
                payload: {
                    postData: {
                        pk_org: emp.orgValue.refpk,
                        transType: emp.leaveType.refpk
                    }
                }
            });
            if(res.success) {
                if(res.data && res.data.message) {
                    this.toast({
                        color: 'danger',
                        content: res.data.message
                    });
                    return;
                }
                await this.update({
                    page: 'add'
                });
                let {
                    form: {
                        head: {
                            card
                        }
                    },
                    newinfo,
                    oldinfo
                } = res.data;

                let template = meta.getMeta();
                // 使用form的api设置的突然失效，直接在模板里修改
                template['card'].items.map((item) => {
                    if (item.attrcode === 'bill_code') {
                        item.disabled = !res.data.isBillCodeEditable
                    } 
                })
                template['psninfo'].items.map((item) => {
                    if (item.attrcode === 'pk_psnjob') {
                        item.disabled = false;
                    }
                })
                template['newinfo'] = newinfo;
                template['oldinfo'] = oldinfo;

                template['newinfo'].items.forEach((item) => {
                    if(['newpk_org', 'newpk_psncl', 'newpk_dept'].includes(item.attrcode)) {
                        item.disabled = false;
                    }
                });

                // 重置黑名单的必填属性
                template['execinfo'].items.forEach((item) => {
                    if(item.attrcode === 'addreason') {
                        item.required = false;
                        item.disabled = true;
                    }
                });
               // 模板不知为啥修改不生效  先用表单api设置
                form.setFormItemsDisabled('card', {'addreason': true})
                form.setFormItemsRequired('card', {'addreason': false})
                Object.keys(template).map((key) => {
                    let tmp = template[key];
    
                    if(tmp && tmp.moduletype === 'form') {
                        tmp.items.map((item) => {
                            if(!item.queryCondition) {
                                item.queryCondition = {};
                            }
                        });
                    }
                });
 
                Object.keys(emp.initValue).forEach((key) => {
                    if(!card.rows[0].values[key] || !('value' in card.rows[0].values[key])) {
                        card.rows[0].values[key] = emp.initValue[key]
                    }
                });
                
                meta.setMeta(template, ()=>{
                    this.toEditStatus(card, {
                        bill_code: !res.data.isBillCodeEditable,
                        pk_psnjob: false
                    });
                });
               
            }
        }
        catch(e) {
            console.log('toAddPageError', e);
        }
    }

    // 进入到修改页面
    toEditPage = async (selectedRows, formValue, ...others) => {
        const {props} = this.comp;
        const {form, dispatch, button, emp, meta} = props;

        this.clearFormValue();
        let postData = {
            billid: selectedRows[0].values['pk_hi_stapply'].value,
            isapprove: emp.fromApprove,
            pk_org: emp.orgValue ? emp.orgValue.refpk : businessInfo.groupId
        };

        // 如果直接传入form表单的值，就直接进来了
        if(formValue) {
            this.update({
                page: 'edit'
            });
            let disabled = {};
            
            if(others && 'isBillCodeEditable' in others) {
                disabled = {
                    bill_code: !others.isBillCodeEditable,
                    pk_psnjob: true
                };
            }
            
            this.toEditStatus(formValue, disabled);

            return;
        }

        let oneBillData = await this.getOneBillData(selectedRows);

        if(oneBillData === false) {
            return;
        }

        try {
            let res = await dispatch({
                type: 'emp/editBill',
                payload: {
                    postData: postData
                }
            });

            if(res.data && res.data.message) {
                this.toast({
                    color: 'danger',
                    content: res.data.message
                });
                return;
            }

            await this.update({
                page: 'edit'
            });
           
            let template = meta.getMeta();
            let {
                form: {
                    head: {
                        card
                    }
                },
                newinfo,
                oldinfo,
                isBillCodeEditable,
                card: cardTmp,
                contorgs,
                execinfo,
                neworgs,
                psninfo
            } = res.data;
            template['card'] = cardTmp
            template['newinfo'] = newinfo;
            template['oldinfo'] = oldinfo;
            template['contorgs'] = contorgs;
            template['execinfo'] = execinfo;
            template['neworgs'] = neworgs;
            template['psninfo'] = psninfo;
                // 模板不知为啥修改不生效  先用表单api设置
            execinfo.items.forEach((item) => {
                if(item.attrcode === 'addreason') {
                    form.setFormItemsDisabled('card', {'addreason': item.disabled})
                    form.setFormItemsRequired('card', {'addreason': item.required})
                }
            })
            Object.keys(template).map((key) => {
                let tmp = template[key];

                if(tmp && tmp.moduletype === 'form') {
                    tmp.items.map((item) => {
                        if(!item.queryCondition) {
                            item.queryCondition = {};
                        }
                    });
                }
            });
            meta.setMeta(template,(r)=>{
                this.toEditStatus(card, {
                    bill_code: !isBillCodeEditable,
                    pk_psnjob: true
                });
            })
           
            
        }
        catch(e) {
            console.error(e);
        }
    }

    // 清空form
    clearFormValue = () => {
        const {props} = this.comp;
        const {form, dispatch, button, emp} = props;

        form.setAllFormValue({
            card: {
                rows: [{
                    values: {
                    }
                }]
            }
        });
    }

    // 直接进入预览页面
    toBrowsePage = async (selectedRows, formValue) => {
        const {props} = this.comp;
        const {form, dispatch, button, emp, meta} = props;

        this.clearFormValue();
        if(formValue) {
            this.toBrowseStatus(formValue);
            return;
        }
        const template = meta.getMeta();

        try {
            let oneBillData = await this.getOneBillData(selectedRows);

            if(oneBillData) {
                this.update({
                    page: 'edit'
                });
            }
            console.log(oneBillData);
            if(oneBillData.data.newinfo) {
                template['newinfo'] = oneBillData.data.newinfo;
            }
            if(oneBillData.data.oldinfo) {
                template['oldinfo'] = oneBillData.data.oldinfo;
            }
            meta.setMeta(template);
            let isApprove = oneBillData.data && oneBillData.data.isApprove
            this.toBrowseStatus(oneBillData.data.form.head.card, isApprove);
        }
        catch(e) {
            console.error('toBrowsePage', e);
        }
    }

    // 获取一条数据
    getOneBillData = async (selectedRows) => {
        const {props} = this.comp;
        const {form, dispatch, button, emp} = props;

        let postData = {
            billid: selectedRows[0].values['pk_hi_stapply'].value,
            pk_org: emp.orgValue ? emp.orgValue.refpk : businessInfo.groupId
        };

        try {
            let res = await dispatch({
                type: 'emp/getOneBillData',
                payload: {
                    postData: postData
                }
            });

            if(res.success) {
                this.update({
                    addPageHistoryData: this.deepCopy(res.data.form.head.card)
                });
                return res;
            }
        }
        catch(e) {
            console.error(e);
        }

        return false;
    }
}